/*
 * BackgroundImageShuffler - Wallpaper changer for Android
 * Copyright (C) 2011 Juhana Paavola <juhana.paavola@gmail.com>
 *
 * This file is part of BackgroundImageShuffler.
 *
 * BackgroundImageShuffler is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * BackgroundImageShuffler is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * You should have received a copy of the GNU Lesser General Public License
 * along with BackgroundImageShuffler.  If not, see <http://www.gnu.org/licenses/>.
*/
package com.juhanapaavola.widget;

import java.io.File;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.format.Time;
import android.widget.RemoteViews;

public class BISProvider extends AppWidgetProvider {
	
	public static File mWallpaper = null;

	public static String CUSTOM_UPDATE="CUSTOM_UPDATE";	

	public static AlarmManager mAlarmManager = null;
	public static PendingIntent mAlarmIntent = null;
	public static Intent mService = null;
	
	@Override
	public void onDeleted(Context context, int[] appWidgetIds) {
		try{
			mAlarmManager.cancel(mAlarmIntent);
		}catch (Exception e) {
			e.printStackTrace();
		}
		try{
			context.stopService(mService);
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void onDisabled(Context context) {
		try{
			mAlarmManager.cancel(mAlarmIntent);			
		}catch (Exception e) {
			e.printStackTrace();
		}
		try{
			context.stopService(mService);
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	@Override
	public void onReceive(Context context, Intent intent) {
		Bundle extras = null;
		
		if(context != null && intent != null){
			extras = intent.getExtras();
			AppWidgetManager awm = AppWidgetManager.getInstance(context);
			int wid = AppWidgetManager.INVALID_APPWIDGET_ID;
			try{
				if(extras != null)
					wid = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
			}catch(NullPointerException e){
				e.printStackTrace();
			}
			
			if(AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(intent.getAction()) ||
					AppWidgetManager.ACTION_APPWIDGET_DISABLED.equals(intent.getAction()) ){
				
				if(mService!=null)
					context.stopService(mService);
				
				if(mAlarmManager != null){
					try{
						mAlarmManager.cancel(mAlarmIntent);
					}catch (Exception e) {
						e.printStackTrace();
					}
				}				
				mAlarmManager = null;

			}else if(CUSTOM_UPDATE.equals(intent.getAction()) ){				
				updateAppWidgetScreen(context, awm, wid,true);
			}else if(AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(intent.getAction())){
				updateAppWidgetScreen(context, awm, wid,false);
			}
		}

	}
	
	
	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {

		final int max = appWidgetIds.length;
		if(max > 0){
			for(int i=0;i<max;i++){		
				int widgetId = appWidgetIds[i];
				updateAppWidget(context, appWidgetManager, widgetId);
			}
		}		
	}

		
	static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId) {
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.main);     
        SharedPreferences prefs = context.getSharedPreferences(BISConfigure.PREF_NAME, 0);
        boolean active = prefs.getBoolean(BISConfigure.PREF_ACTIVATED, false);
        
    	Intent intent = new Intent(BISProvider.CUSTOM_UPDATE);
    	intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);

    	// set alarm service for us
    	BISProvider.mAlarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
    	BISProvider.mAlarmIntent = PendingIntent.getBroadcast(context, appWidgetId, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        
        if(active){
        	if(mAlarmManager != null){
        		if(mAlarmIntent != null)
        			mAlarmManager.cancel(mAlarmIntent);
        	}
        
        	
        	boolean scheduled = prefs.getBoolean(BISConfigure.PREF_USE_SCHEDULED, false);        	
        	Time nextTime = new Time();
    		int hour = prefs.getInt(BISConfigure.PREF_USE_SCHEDULED_HOUR, 0);
    		int minute = prefs.getInt(BISConfigure.PREF_USE_SCHEDULED_MINUTE, 0);
        	
        	if(scheduled){
        		nextTime.set(System.currentTimeMillis());
        		int day = nextTime.monthDay;
        		Time cur = new Time();
        		cur.set(System.currentTimeMillis());
        		if(hour<cur.hour || minute<cur.minute)
        			day+=1;
        		nextTime.set(0, minute, hour, day, nextTime.month, nextTime.year);
        		
        		BISProvider.mAlarmManager.setRepeating(AlarmManager.RTC, nextTime.toMillis(false), AlarmManager.INTERVAL_DAY, BISProvider.mAlarmIntent);
        	}else{
        		
        		int nexthour = hour*60*60*1000;
        		int nextmin = minute*60*1000;
        		int nexttotal = nexthour+nextmin;
        		            	
            	BISProvider.mAlarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis(), nexttotal, BISProvider.mAlarmIntent);
        	}
        	        	
        }else if(!active){
        	if(BISProvider.mAlarmManager != null){
            	try{
            		BISProvider.mAlarmManager.cancel(mAlarmIntent);
            	}catch (NullPointerException e) {
    				e.printStackTrace();    				
    				BISProvider.mAlarmManager = null;
    			}        	
        	}
        }
        
		Intent ci = new Intent(context, BISConfigure.class);
		ci.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
        PendingIntent pi = PendingIntent.getActivity(context, appWidgetId, ci, 0);
        views.setOnClickPendingIntent(R.id.imageView1, pi);
        
        appWidgetManager.updateAppWidget(appWidgetId, views);
    }

	static void updateAppWidgetScreen(Context context, AppWidgetManager appWidgetManager, int appWidgetId, boolean changeImage) {
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.main);

        if(changeImage){
        	mService = new Intent(context, BISService.class);
        	context.startService(mService);
        }
        
		Intent intent = new Intent(context, BISConfigure.class);
		intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);

        PendingIntent pi = PendingIntent.getActivity(context, appWidgetId, intent, 0);
        views.setOnClickPendingIntent(R.id.imageView1, pi);
        
        appWidgetManager.updateAppWidget(appWidgetId, views);
	}
	
	static void cancelAlarmService(Context context){
		if(BISProvider.mService != null)
			context.stopService(BISProvider.mService);
    	if(BISProvider.mAlarmManager != null){
        	try{
        		BISProvider.mAlarmManager.cancel(BISProvider.mAlarmIntent);
        	}catch (NullPointerException e) {
				e.printStackTrace();    				
				BISProvider.mAlarmManager = null;
			}        	
    	}		
	}
}
